package com.bigshen.springcloud.controller;

import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class HystrixController {

    @Autowired
    RestTemplate restTemplate;

    /**
     * 3种降级方案：
     * a. fallback -> 回退方案(降级处理方案) {@link HystrixCommandProperties}内有所有属性
     *
     * @param num
     * @return
     */
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), // 开启熔断
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "5"), //最小请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000"), //时间窗口，熔断后这段时间直接返回 callback
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50") // 百分比
    }, fallbackMethod = "myFallBack") // 接口异常返回兜底数据
    @GetMapping("/hystrix/order/{num}")
    public String queryOrder(@PathVariable("num") int num) {
        // 服务宕机，没有启动
        if (num % 2 == 0) {
            return "正常访问";
        }
        return restTemplate.getForObject("http://127.0.0.1:8182/order", String.class);
    }

    public String myFallBack(int num) {
        // 返回兜底数据
        return "系统繁忙";
    }

    @HystrixCommand(
            commandProperties = {
              @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")  // 超时时间
            },
            fallbackMethod = "myTimeOutFallBack")
    @GetMapping("/hystrix/timeout")
    public String queryOrderTimeOut() {
        return restTemplate.getForObject("http://127.0.0.1:8082/order", String.class);
    }


    public String myTimeOutFallBack() {
        return "系统请求超时";
    }

}
